package com.example.flight.controller;


import java.util.Date;



import com.example.flight.common.BuyException;
import com.example.flight.common.JwtUtils;
import com.example.flight.common.Result;

import com.example.flight.service.FlightInformationService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.example.flight.entity.OrderEntity;
import com.example.flight.service.OrderService;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author hws
 * @email 231884142@qq.com
 * @date 2023-06-12
 */
@RestController
@RequestMapping("/orders")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private FlightInformationService flightInformationService;
    /**
     * 列表
     */
    @GetMapping()
    public Result myList(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring("Bearer ".length());
        }
        Claims claims = JwtUtils.getClaimsByToken(token);


        return Result.ok().data("list", orderService.listByUid((String) claims.get("id")));
    }
    /**
     * listByIDNum
     */
    @GetMapping("{id}")
    public Result listByIDNum(@PathVariable("id")String  identityNumber){

        return Result.ok().data("list", orderService.listByIDNum(identityNumber));
    }

    /**
     * 列表
     */
    @GetMapping("/admin")
    public Result list(){

        return Result.ok().data("list", orderService.list() );
    }



    /**
     * 保存
     */
    @PostMapping()
    public Result save(@RequestBody OrderEntity order, HttpServletRequest request) throws BuyException {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring("Bearer ".length());
        }
        Claims claims = JwtUtils.getClaimsByToken(token);
        order.setUid((String) claims.get("id"));
        order.setCreateTime(new Date());
        orderService.buy(order);
        return Result.ok();
    }



    /**
     * 删除
     */
    @DeleteMapping("/{oid}")
    public Result delete(@PathVariable("oid") String oid){
        orderService.removeById(oid);

        return Result.ok();
    }

}
